﻿using System;
using System.Diagnostics;


namespace CacheDependencyManagerWindowsService
{
    using System.Configuration;
    using System.ServiceProcess;
    using CacheProviderInterfaces;
    using CacheProvider;
    using CacheProviderUtilities;
    using CacheProviderEntities;
    

    public partial class CacheDependencyMgrWinSvc : ServiceBase
    {
        private CacheDependencyProcessor _cacheDependencyProcessor;
        private ILogWriter _logWriter;

        public CacheDependencyMgrWinSvc()
        {
            InitializeComponent();
            AppDomain.CurrentDomain.UnhandledException += this.CurrentDomain_UnhandledException;
        }

        protected void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
        {
            if (this._logWriter == null) return;

            var exception = e.ExceptionObject as Exception;
            if (exception != null)
                this._logWriter.Write(exception.Message, "TomcatLogging", 1, (int)CacheOperation.DependencyMonitorSvc, TraceEventType.Error, ConfigurationManager.AppSettings["ApplicationName"]);
        }

        protected override void OnStart(string[] args)
        {
            this._logWriter = new EntLibLogWriter();
            this._cacheDependencyProcessor = new CacheDependencyProcessor();
            var dependencyCacheKey = ConfigurationManager.AppSettings["DependenciesCacheKey"];
            var dependencyNotificationProcessingDelayInSeconds = Convert.ToInt32(ConfigurationManager.AppSettings["DependencyNotificationProcessingDelayInSeconds"]);
            this._cacheDependencyProcessor.StartMonitoringDepdencies(dependencyCacheKey, dependencyNotificationProcessingDelayInSeconds);
            const string message = "Cache Dependency Monitor Windows Service Started";
            this._logWriter.Write(message, "TomcatLogging", 1, (int)CacheOperation.DependencyMonitorSvc, TraceEventType.Information, ConfigurationManager.AppSettings["ApplicationName"]);
        }

        public void ConsoleStart()
        {
            this.OnStart(null);
        }

        protected override void OnStop()
        {
            this._cacheDependencyProcessor.StopMonitoring();
        }
    }
}
